package com.example.experiment_four;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class BindService extends Service {
    private int count;
    private boolean quit;
    private MyBinder binder = new MyBinder();
    public class MyBinder extends Binder {
        public int getCount() {
            return count;
        }
    }
    // 必须实现方法，绑定该Service时回调该方法
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("Service is Binded");
        return binder;
    }
    //Service被创建时回调该方法
    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("Service is Created");
        new Thread()
        {
            @Override
            public void run() {
                while (!quit) {
                    try {
                        Thread.sleep(1000);
                    }
                    catch (InterruptedException e) {
                        //e.printStackTrace();
                    }
                    count++;
                }
            }
        }.start();
    }
    //Service被断开连接时回调该方法
    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("Service is Unbinded");
        return true;
    }
    // Service被关闭之前回调该方法。
    @Override
    public void onDestroy() {
        super.onDestroy();
        this.quit = true;
        System.out.println("Service is Destroyed");
    }
}